package es.ibm.santillana.mdm.entryPreview.catalog;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ibm.ccd.common.context.AustinContext;
import com.ibm.json.java.JSONArray;
import com.ibm.json.java.OrderedJSONObject;
import com.ibm.pim.attribute.AttributeInstance;
import com.ibm.pim.catalog.Catalog;
import com.ibm.pim.catalog.CatalogManager;
import com.ibm.pim.catalog.item.Item;
import com.ibm.pim.common.exceptions.PIMSearchException;
import com.ibm.pim.context.Context;
import com.ibm.pim.context.PIMContextFactory;
import com.ibm.pim.lookuptable.LookupTable;
import com.ibm.pim.lookuptable.LookupTableEntry;
import com.ibm.pim.lookuptable.LookupTableManager;
import com.ibm.pim.search.SearchQuery;
import com.ibm.pim.search.SearchResultSet;
import com.ibm.pim.web.framework.dispatcher.AsyncEnabled;
import com.ibm.pim.web.framework.dispatcher.RequestResponseEnabled;

import es.ibm.santillana.mdm.common.util.ConstSantillana;

public class PackViewer implements AsyncEnabled,RequestResponseEnabled{
	
	private static String sSpecName = "Articulos CPS";
	HttpServletRequest request;
	HttpServletResponse response;
	Context ctxPIM;
	CatalogManager ctgMan;
	Catalog masterCatalog;
	
	//send an json array
	String responseContent ="";

	/* (sin Javadoc) 
	 * @see com.ibm.pim.web.framework.dispatcher.AsyncEnabled#getContentType()
	 */
	public String getContentType() {
		
		return JSON;
	}

	/* (sin Javadoc)
	 * @see com.ibm.pim.web.framework.dispatcher.AsyncEnabled#getResponseContent()
	 */
	public String getResponseContent() {
		
		return responseContent;
	}

	/* (sin Javadoc)
	 * @see com.ibm.pim.web.framework.dispatcher.RequestResponseEnabled#setRequest(javax.servlet.http.HttpServletRequest)
	 */
	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	/* (sin Javadoc)
	 * @see com.ibm.pim.web.framework.dispatcher.RequestResponseEnabled#setResponse(javax.servlet.http.HttpServletResponse)
	 */
	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}
	
	/**
	 * Init variables context, catalog and CatalogManager
	 */
	public void initPacks(){
		if(masterCatalog==null){
			if(ctgMan==null){
				if(ctxPIM==null){
					ctxPIM = PIMContextFactory.getCurrentContext();
				}
				ctgMan = ctxPIM.getCatalogManager();
			}
			masterCatalog = ctgMan.getCatalog(ConstSantillana.MAESTRO_ARTICULOS);
		}
	}
	
	/**
	 * Obtains from request Item Pk and URL to get required pack info 
	 * to send data with Ajax.
	 * @throws IOException - If there are errors with the serialize
	 */
	public void getPacksData() throws IOException{
		
		AustinContext actx = (AustinContext)request.getSession().getAttribute("ctx");
		AustinContext.setCurrentContext(actx);
		String sPk = request.getParameter("PK");
		String sUrl = request.getParameter("URL");
		initPacks();
		JSONArray aListOrden = getPackInfo(sPk,sUrl);
		responseContent = aListOrden.serialize(true);
		
	}
	
	/**
	 * @param pkPack
	 */
	public void getRelatedPacks() {
		AustinContext actx = (AustinContext)request.getSession().getAttribute("ctx");
		AustinContext.setCurrentContext(actx);
		initPacks();
		JSONArray aListOrden = new JSONArray();
		String sPk = request.getParameter("PK");
		String sUrl = request.getParameter("URL");
		String sQuery = "select item from catalog('Maestro Articulos') "+ 
		                "where item['Articulos CPS/Packs/ArticuloRelacionado'].pk = '"+sPk+"'";
		SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
		SearchResultSet resSet = searchQ.execute();
		
		Integer contador = 0;
		while(resSet.next()){
			try {
				aListOrden.add(getItemobject(resSet.getItem(1),++contador,sUrl));
			} catch (PIMSearchException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		try {
			responseContent = aListOrden.serialize(true);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * Check if a is a pack item.
	 * @param item - item to check.
	 * @return true if is a pack or false if not.
	 */
	private Boolean isPack(Item item){
		AttributeInstance attInstancePacks =  item.getAttributeInstance(sSpecName + "/Packs");
		if(attInstancePacks!=null){
			List<AttributeInstance> packs = (List<AttributeInstance>) attInstancePacks.getChildren();
			if(packs!=null && packs.size()>0){
				return true;
			}
		}
		return false;
	}
	
	//http://10.125.143.100:7507/Prueba.wpc?PK=34554135&User=Admin&Padre=true&Titulo=Asignaturas
	
	/**
	 * Build a link using input parameters.
	 * @param pkFinal
	 * @param tituloFinal
	 * @param urlOriginal
	 * @return
	 */
	private String buildIP(String pkFinal, String tituloFinal, String urlOriginal){
		int separaIP = urlOriginal.indexOf(".wpc?PK");
		int separa1 = urlOriginal.indexOf("&User=");
		int separa2 = urlOriginal.indexOf("&Padre=");
		return urlOriginal.substring(0, separaIP + 8) + pkFinal + urlOriginal.substring(separa1, separa2) + "&Padre=false&Titulo=" + tituloFinal;
	}
	
	private String createLink(String sPk,String url, String titulo){
		Item item = masterCatalog.getItemByPrimaryKey(sPk);
		if(isPack(item)){
			return "<A href=\"" + buildIP(sPk,titulo,url) + "\" title=\"Ir al Pack.\">" + sPk + "</A>";
		}
		else{
			return "No";
		}
	}
	
	private String createImageLink(String sPk){
		Item item = masterCatalog.getItemByPrimaryKey(sPk);
		AttributeInstance atiImagen = item.getAttributeInstance(sSpecName + "/ImagenLibro");
		if(atiImagen!=null){
			
		}
		String link = (String) item.getAttributeValue(sSpecName + "/ImagenLibro");
		if(link!=null){
			
			LookupTableManager lkpMan = PIMContextFactory.getCurrentContext().getLookupTableManager();
			LookupTable lkp =  lkpMan.getLookupTable(ConstSantillana.LOOKUP_SYSTEM);
			LookupTableEntry lkpEntry = lkp.getLookupTableEntry("company");
			String sCompany = (String) lkpEntry.getAttributeValue("Code_Value_LTS/Value");
			
			return "<img src=\"/suppliers/"+sCompany+"/ctg_files/"+ link+"\" alt=\"Imagen del articulo.\" width=\"60\" height=\"80\">";
		}
		else{
			return "";
		}
	}
	
	/**
	 * Build a JSON object to send to DOJO Jsp.
	 * @param item
	 * @param orden
	 * @param sURL
	 * @return
	 */
	private OrderedJSONObject getItemobject(Item item,Integer orden, String sURL){
		OrderedJSONObject obj = new OrderedJSONObject();
		String sPk = item.getPrimaryKey();
		String titulo = (String) item.getAttributeValue(sSpecName + "/General/TituloCorto");
		String isbn = (String) item.getAttributeValue(sSpecName + "/Control/ISBN");
		obj.put("Orden", orden.toString());
		obj.put("Titulo", titulo);
		obj.put("ISBN", isbn);
		obj.put("Numero","1");
		obj.put("Imagen", createImageLink(sPk));
		obj.put("Link",createLink(sPk,sURL,titulo));
		return obj;
	}
	
	private OrderedJSONObject getPackobject(String attributeInstancePath, Item item, Catalog catalogo,String sURL){
		OrderedJSONObject obj = new OrderedJSONObject();
		String sPkitemRelacionado = (String) item.getAttributeValue(attributeInstancePath + "/ArticuloRelacionado");
		Item itemRelacionado = catalogo.getItemByPrimaryKey(sPkitemRelacionado);
		String tituloRelacionado = (String) itemRelacionado.getAttributeValue(sSpecName + "/General/TituloCorto");
		String isbnRelacionado = (String) itemRelacionado.getAttributeValue(sSpecName + "/Control/ISBN");
		Integer numeroArticulos = (Integer) item.getAttributeValue(attributeInstancePath + "/NumeroArticulos");
		Integer orden = (Integer) item.getAttributeValue( attributeInstancePath+ "/Orden");
		obj.put("Orden", orden.toString());
		obj.put("Titulo", tituloRelacionado);
		obj.put("ISBN", isbnRelacionado);
		obj.put("Numero",numeroArticulos.toString());
		obj.put("Imagen", createImageLink(sPkitemRelacionado));
		obj.put("Link",createLink(sPkitemRelacionado,sURL,tituloRelacionado));
		System.out.println("Item: " + sPkitemRelacionado + " numero: " + numeroArticulos + " orden: " + orden);
		return obj;
	}
	
	private JSONArray getPackInfo(String sPk,String sURL){
		JSONArray aListOrden = new JSONArray();
		Catalog catalogo = ctgMan.getCatalog(ConstSantillana.MAESTRO_ARTICULOS);
		Item item = catalogo.getItemByPrimaryKey(sPk);
		AttributeInstance attInstancePacks =  item.getAttributeInstance(sSpecName + "/Packs");
		List<AttributeInstance> packs = null;
		if(attInstancePacks!=null){
			packs = (List<AttributeInstance>) attInstancePacks.getChildren();
			if(packs!=null && packs.size()>0){
				for(AttributeInstance attInstanceTemp : packs){
					aListOrden.add(getPackobject(attInstanceTemp.getPath(), item, catalogo,sURL));
				}
			}
		}
		return aListOrden;
	}
	
}
